package com.moli.iov.gateway.util.logger;


import net.jodah.expiringmap.ExpiringMap;
import org.apache.log4j.*;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.concurrent.TimeUnit;


/**
 * @author fudh
 * @ClassNmme GatewayLogger
 * @date 2018/12/20 13:50
 * @Description: TODO
 */
public class GatewayLogger {

    private static ExpiringMap<String, GeteWayRollingFileAppender> fileAppenderMap = null;
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    static {
        Integer remainSecondsOneDay = getRemainSecondsOneDay(new Date());
        //获取距离当天结束还剩多少秒
        fileAppenderMap = ExpiringMap.builder()
                .expiration(remainSecondsOneDay, TimeUnit.SECONDS)
                .expirationListener((fileName, appender) -> {
                    //过期时候重新设置过期时间
                    int remainSecondsOneDay1 = getRemainSecondsOneDay(new Date());
                    fileAppenderMap.setExpiration(remainSecondsOneDay1, TimeUnit.SECONDS);
                    long expiration = fileAppenderMap.getExpiration();
                })
                .build();
    }

    public static Logger getLogger(String vin, String path) {
        // 日志文件按照每天分文件夹存放
        String dateFormt = sdf.format(new Date());
        //日志路径
        String logPath = path + dateFormt + File.separator;
//        try {
//            checkFileExist(logPath,vin);
//        } catch (IOException e) {
//            logger1.error("创建日志失败!");
//            e.printStackTrace();
//        }
        String appendName = dateFormt + "-" + vin;
        String fileName = logPath + vin + ".log";
        Logger logger = Logger.getLogger(vin);
        //清空所有的appender，保证同时只有一个
        logger.setLevel(Level.INFO);
        GeteWayRollingFileAppender fileAppender = fileAppenderMap.get(appendName);
        if (fileAppender == null) {
            try {
                logger.removeAllAppenders();
                PatternLayout layout = new PatternLayout("[%d{MM-dd HH:mm:ss}]  %m%n");
                fileAppender = new GeteWayRollingFileAppender(layout, fileName, true);
                fileAppender.setName(appendName);
                fileAppender.setAppend(false);
                fileAppender.setImmediateFlush(true);
                fileAppender.setThreshold(Level.INFO);
                fileAppenderMap.put(appendName, fileAppender);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        logger.addAppender(fileAppender);
        return logger;
    }

    public static class GeteWayRollingFileAppender extends RollingFileAppender {
        public GeteWayRollingFileAppender(Layout layout, String fileName, boolean appened)
                throws IOException {
            super(layout, fileName, appened);
        }

    }

    /***
     * 获取当前时间到当天24点结束还有多少秒
     * @param currentDate
     * @return
     */
    public static Integer getRemainSecondsOneDay(Date currentDate) {
        LocalDateTime midnight = LocalDateTime.ofInstant(currentDate.toInstant(),
                ZoneId.systemDefault())
                .plusDays(1)
                .withHour(0)
                .withMinute(0)
                .withSecond(0)
                .withNano(0);
        LocalDateTime currentDateTime = LocalDateTime.ofInstant(currentDate.toInstant(), ZoneId.systemDefault());
        long seconds = ChronoUnit.SECONDS.between(currentDateTime, midnight);
        return (int) seconds;
    }

//    public static void main(String[] args) {
//        Integer remainSecondsOneDay = getRemainSecondsOneDay(new Date());
//        System.out.println(remainSecondsOneDay);
//    }

//    public  void MM imple


//    public  static  void checkFileExist(String path,String vin) throws IOException {
//
//        File file = new File(path+vin+".log");
//        if(!file.exists()){
//            file.createNewFile();
//        }
//    }
}
